const host = window.location.host;
const API_BASE_URL = "http://" + host;
const apiUrl = {
    user: {
        userPage: API_BASE_URL + '/user/page',
        ready2Sending: API_BASE_URL + '/user/ready-for-sending',
    },
    kf: {
        sendTextMessage: API_BASE_URL + '/kf/send-text'
    },
    ws: {
        newMessage: `ws://${host}/new-message-notifier`
    },
    material: {
        create: API_BASE_URL + '/material/create',
        page: API_BASE_URL + '/material/page',
        newsPage: API_BASE_URL + '/material/news'
    },
    autoReplyRule: {
        page: API_BASE_URL + '/auto-reply-rule/page',
        create: API_BASE_URL + '/auto-reply-rule/create',
        delete: API_BASE_URL + '/auto-reply-rule/delete'
    },
    admin: {
        checkStatus: API_BASE_URL + '/admin-public/account',
        list: API_BASE_URL + '/admin/list',
        delete: API_BASE_URL + '/admin/delete',
        bindQrCode: '/admin/bind-open-id-qrcode?adminId='
    }
};

const Util = {
    showTmpWindow(title, w, h, content) {
        const wd = $('<div></div>');
        wd.appendTo('body');
        wd.append(content);
        wd.window({
            title: title,
            width: w,
            height: h,
            modal: true
        });
    },
    getSelectedRow(tb, fn) {
        const row = tb.datagrid('getSelected');
        if (row) {
            fn(row);
            return row;
        } else {
            $.messager.alert('提示', '请选择一行', 'info');
            return null;
        }
    },
    show(data) {
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        if (data.code === 0) {
            $.messager.show({
                title: '提示',
                msg: data.msg
            });
        } else {
            $.messager.alert('错误', data.msg, 'error');
        }
    },
    checkLoginStatus(callback) {
        $.get(apiUrl.admin.checkStatus, res => {
            callback(res);
        }, 'json')
    }
};

function Context() {
    this._services = {};
    this._menu = null;
    this._tab = null;
    this._tables = {};
    this._windows = {};
    this._components = {};
    this._form = {};
}

Context.prototype = {
    service(name, service) {
        if (service) {
            this._services[name] = service;
        } else {
            service = this._services[name];
        }
        return service;
    },
    menu(menu) {
        if (menu) {
            this._menu = menu;
        } else {
            return this._menu;
        }
    },
    tab(tab) {
        if (tab) {
            this._tab = tab;
        } else {
            return this._tab;
        }
    },
    table(name, table) {
        if (table) {
            this._tables[name] = table;
        } else {
            return this._tables[name];
        }
    },
    window(name, wd) {
        if (wd) {
            this._windows[name] = wd;
        } else {
            return this._windows[name];
        }
    },
    component(name, component) {
        if (component) {
            this._components[name] = component;
        } else {
            return this._components[name];
        }
    },
    form(name, form) {
        if (form) {
            this._form[name] = form;
        } else {
            return this._form[name];
        }
    }
};

function Menu(context) {
    const _this = this;
    context.menu(this);
    this.context = context;
    this.menuTemplate = [
        {
            text: '用户管理',
            iconCls: 'icon-man',
            handler: () => {
                const panel = context.tab().addOrSelect({
                    title: '用户管理',
                    iconCls: 'icon-man'
                });
                if (panel) {
                    const tb = $('<div>hello</div>');
                    panel.append(tb);
                    _this.context.table('user', tb);
                    _this.context.service('user').genPagingUserTable(tb);
                }
            }
        },
        {
            text: '素材管理',
            iconCls: 'icon-large-picture',
            children: [
                {
                    text: '基本素材管理',
                    iconCls: 'icon-large-picture',
                    handler: () => {
                        const panel = context.tab().addOrSelect({
                            title: '素材管理',
                            iconCls: 'icon-large-picture'
                        });
                        if (panel) {
                            const tb = $('<div></div>');
                            context.table('material', tb);
                            panel.append(tb);
                            context.service('material').genMaterialTable(tb);
                        }
                    }
                },
                {
                    text: '图文素材管理',
                    iconCls: 'icon-large-picture',
                    handler: () => {
                        const panel = context.tab().addOrSelect({
                            title: '图文素材管理',
                            iconCls: 'icon-large-picture'
                        });
                        if (panel) {
                            const tb = $('<div></div>');
                            context.table('news-material', tb);
                            panel.append(tb);
                            context.service('material').genNewsMaterialTable(tb);
                        }
                    }
                }
            ]
        },
        {
            text: '自动回复规则管理',
            iconCls: 'icon-reload',
            handler: () => {
                const panel = context.tab().addOrSelect({
                    title: '自动回复规则管理',
                    iconCls: 'icon-reload'
                });
                if (panel) {
                    const tb = $('<div></div>');
                    context.table('autoReplyRule', tb);
                    panel.append(tb);
                    context.service('autoReplyRule').genRuleTable(tb);
                }
            }
        },
        {
            text: '管理员账户编辑',
            iconCls: 'icon-man',
            handler: () => {
                const panel = context.tab().addOrSelect({
                    title: '管理员账户',
                    iconCls: 'icon-man'
                });
                if (panel) {
                    const tb = $('<div></div>');
                    context.table('admin', tb);
                    panel.append(tb);
                    context.service('admin').genAdminTable(tb);
                }
            }
        }
    ];
    this._menuTree = $("#menu-tree");
    this.init();
}

Menu.prototype = {
    init() {
        const _this = this;
        this._menuTree.tree({
            data: _this.menuTemplate,
            onClick: node => {
                if (node.handler) {
                    node.handler(node);
                }
            }
        });
    }
};

function MaterialWindow(context) {
    this.context = context;
    context.window('material', this);
    this._windows = {};
    this.init();
}

MaterialWindow.prototype = {
    init() {
        this.initCreateWindow();
    },
    initCreateWindow() {
        const _this = this;
        const wd = $("#form-material-create");
        this._windows.create = wd;
        wd.dialog({
            title: '创建新素材',
            iconCls: 'icon-add',
            width: 500,
            height: 300,
            closed: true,
            buttons: [
                {
                    text: '创建',
                    iconCls: 'icon-ok',
                    handler: () => {
                        _this.context.form('material').submitCreate();
                    }
                },
                {
                    text: '取消',
                    iconCls: 'icon-cancel',
                    handler: () => {
                        wd.dialog('close');
                    }
                }
            ]
        });
    },
    showCreate() {
        this._windows.create.dialog('open');
    }
};

function AutoReplyRuleWindow(context) {
    this.context = context;
    context.window('auto-reply-rule', this);
    this.windows = {};
    this.init();
}

AutoReplyRuleWindow.prototype = {
    init() {
        this.initCreateWindow();
    },
    initCreateWindow() {
        const _this = this;
        this.windows.create = $("#window-auto-reply-rule-create").dialog({
            title: '创建新规则',
            iconCls: 'icon-add',
            width: 500,
            height: 400,
            closed: true,
            modal: true,
            buttons: [
                {
                    text: '创建',
                    iconCls: 'icon-ok',
                    handler() {
                        _this.context.form('auto-reply-rule').submitCreate();
                    }
                },
                {
                    text: '取消',
                    iconCls: 'icon-cancel',
                    handler() {
                        _this.context.window('auto-reply-rule').windows.create.dialog('close');
                    }
                }
            ]
        });
    },
    showCreate() {
        this.windows.create.dialog('open');
    }
};

function AdminWindow(context) {
    context.window('admin', this);
    this.context = context;
    this.windows = {};
    this.init();
}

AdminWindow.prototype = {
    init() {
        this.initCreateWindow();
        this.initBindWindow();
    },
    initCreateWindow() {
        const _this = this;
        this.windows.create = $("#window-admin-create");
        this.windows.create.dialog({
            title: '创建管理员',
            iconCls: 'icon-add',
            width: 300,
            height: 300,
            closed: true,
            buttons: [
                {
                    text: '确认创建',
                    iconCls: 'icon-ok',
                    handler: () => {
                        _this.context.form('admin').submitCreate();
                    }
                },
                {
                    text: '取消创建',
                    iconCls: 'icon-cancel',
                    handler: () => {
                        _this.closeCreateWindow();
                    }
                }
            ]
        });
    },
    closeCreateWindow() {
        this.windows.create.dialog('close');
    },
    showCreateWindow() {
        this.windows.create.dialog('open');
    },
    initBindWindow() {
        const _this = this;
        this.windows.bind = $("#window-admin-bind").dialog({
            title: '绑定微信号',
            iconCls: 'icon-mini-add',
            width: 300,
            height: 400,
            closed: true,
            buttons: [
                {
                    text: '关闭',
                    iconCls: 'icon-cancel',
                    handler() {
                        _this.closeBindWindow();
                    }
                }
            ]
        });
        this.windows.bind.qrcode = $("#qrcode-admin-bind-openid");
    },
    showBindWindow(adminId) {
        this.windows.bind.qrcode.attr('src', apiUrl.admin.bindQrCode + adminId);
        this.windows.bind.dialog('open');
    },
    closeBindWindow() {
        this.windows.bind.qrcode.attr('src', 'img/loading.gif');
        this.windows.bind.dialog('close');
    }
};

function ContentTab(content) {
    content.tab(this);
    this._tab = $("#content-tab").tabs();
}

ContentTab.prototype = {
    addOrSelect(option) {
        if (this._tab.tabs('exists', option.title)) {
            this._tab.tabs('select', option.title);
        } else {
            option.closable = true;
            this._tab.tabs('add', option);
            return this._tab.tabs('getTab', option.title);
        }
    }
};

function UserService(context) {
    context.service('user', this);
    this.context = context;
    this._columnScheme = [[
        {title: '#', field: 'id', width: 30},
        {title: 'OpenID', field: 'openId', width: 300},
        {title: '最后一次活动时间', field: 'lastActivityTime', width: 200},
    ]];
}

UserService.prototype = {
    genPagingUserTable(tb) {
        const _this = this;
        tb.datagrid({
            url: apiUrl.user.userPage,
            columns: _this._columnScheme,
            method: 'get',
            pagination: true,
            toolbar: [
                {
                    text: '删除',
                    iconCls: 'icon-remove',
                    handler: () => {
                        console.log('test');
                    }
                },
                {
                    text: '可发送客服消息',
                    iconCls: 'icon-search',
                    handler: () => {
                        const tb = $('<div></div>');
                        _this.context.table('ready-to-sending-user', tb);
                        Util.showTmpWindow('可发送客服消息的用户', 800, 300, tb);
                        _this.context.service('user').genReady2SendingUserTable(tb);
                    }
                }
            ]
        });
    },
    genReady2SendingUserTable(tb) {
        const _this = this;
        tb.datagrid({
            url: apiUrl.user.ready2Sending,
            columns: _this._columnScheme,
            method: 'GET',
            toolbar: [
                {
                    text: '发送消息',
                    handler: () => {
                        Util.getSelectedRow(_this.context.table('ready-to-sending-user'), row => {
                            $.messager.prompt('客服消息', '文本消息', r => {
                                _this.context.service('kf').sendTextMessage(row.id, r);
                            });
                        });
                    }
                }
            ]
        });
    }
};

function KfService(context) {
    this.context = context;
    context.service('kf', this);
}

KfService.prototype = {
    sendTextMessage(userId, msg) {
        $.post(apiUrl.kf.sendTextMessage, {userId, msg}, res => {
            let title = '';
            if (res.code === 0) {
                title = '提示';
            } else {
                title = '错误';
            }
            $.messager.show({
                title,
                msg: JSON.stringify(res.data)
            });
        }, 'json');
    }
};

function MaterialService(context) {
    this.context = context;
    context.service('material', this);
    this.columnScheme = [[
        {field: 'id', title: '#', width: 30},
        {field: 'type', title: '类型', width: 50},
        {field: 'mediaId', title: 'MediaID', width: 100},
        {field: 'createAt', title: '创建时间', width: 200},
        {field: 'url', title: '链接地址', width: 200},
        {field: 'title', title: '标题', width: 200},
        {field: 'introduction', title: '备注', width: 200}
    ]]
}

MaterialService.prototype = {
    genMaterialTable(tb) {
        const _this = this;
        tb.datagrid({
            url: apiUrl.material.page,
            method: 'GET',
            columns: _this.columnScheme,
            pagination: true,
            toolbar: [
                {
                    text: '创建',
                    iconCls: 'icon-add',
                    handler: () => {
                        _this.context.window('material').showCreate();
                    }
                },
                {
                    text: '创建图文素材',
                    iconCls: 'icon-add',
                    handler: () => {
                        $.messager.alert('提示', '暂不支持，请直接前往公众号后台编辑', 'info');
                    }
                }
            ]
        });
    },
    genNewsMaterialTable(tb) {
        tb.datagrid({
            url: apiUrl.material.newsPage,
            columns: [[
                {field: 'mediaId', title: '素材ID', width: 200},
                {field: 'content', title: '内容', width: 300, formatter: JSON.stringify}
            ]],
            pagination: true,
            method: 'GET',
            singleSelect: true
        });
    }
};

function AutoReplyRuleService(context) {
    this.context = context;
    context.service('autoReplyRule', this);
    this.columnScheme = [[
        {field: 'id', title: '#', width: 30},
        {field: 'msg', title: '用户发送消息', width: 100},
        {field: 'replyType', title: '回复消息类型', width: 100},
        {field: 'rule', title: '规则', width: 100},
        {field: 'mediaId', title: '素材ID', width: 100},
        {field: 'title', title: '标题', width: 100},
        {field: 'description', title: '描述', width: 100},
        {field: 'url', title: '链接地址', width: 100},
        {field: 'picUrl', title: '图片地址', width: 100},
        {field: 'content', title: '文本内容', width: 200}
    ]];
}

AutoReplyRuleService.prototype = {
    genRuleTable(tb) {
        const _this = this;
        tb.datagrid({
            url: apiUrl.autoReplyRule.page,
            method: 'GET',
            columns: _this.columnScheme,
            pagination: true,
            singleSelect: true,
            toolbar: [
                {
                    text: '新建规则',
                    iconCls: 'icon-add',
                    handler: () => {
                        _this.context.window('auto-reply-rule').showCreate();
                    }
                },
                {
                    text: '删除规则',
                    iconCls: 'icon-remove',
                    handler() {
                        Util.getSelectedRow(tb, row => {
                            _this.context.service('autoReplyRule').delete(row.id);
                        });
                    }
                }
            ]
        });
    },
    delete(id) {
        $.post(apiUrl.autoReplyRule.delete, {id}, res => {
            Util.show(res);
        }, 'json');
    }
};

function AdminService(context) {
    context.service('admin', this);
    this.context = context;
    this.columns = [[
        {field: 'id', title: '#', width: 30},
        {field: 'name', title: '账户', width: 200},
        {field: 'password', title: '密码', width: 300},
        {field: 'openId', title: '微信号', width: 300, formatter: v => v ? '已绑定{' + v + '}' : '未绑定'},
    ]];
}

AdminService.prototype = {
    genAdminTable(tb) {
        const _this = this;
        tb.datagrid({
            url: apiUrl.admin.list,
            method: 'get',
            pagination: true,
            columns: _this.columns,
            singleSelect: true,
            toolbar:
                [
                    {
                        text: '删除',
                        iconCls: 'icon-remove',
                        handler: () => {
                            Util.getSelectedRow(tb, row => {
                                _this.context.service('admin').delete(row);
                            });
                        }
                    },
                    {
                        text: '创建',
                        iconCls: 'icon-add',
                        handler: () => {
                            _this.context.window('admin').showCreateWindow();
                        }
                    },
                    {
                        text: '绑定微信号',
                        iconCls: 'icon-mini-add',
                        handler: () => {
                            Util.getSelectedRow(tb, row => {
                                _this.context.window('admin').showBindWindow(row.id);
                            });
                        }
                    }
                ]
        });
    },
    delete(row) {
        const _this = this;
        $.messager.confirm('确认删除', '确认删除管理员' + row.name + '么？', r => {
            if (r) {
                $.post(apiUrl.admin.delete, row, res => {
                    Util.show(res);
                    _this.context.table('admin').datagrid('reload');
                });
            }
        });
    }
};

function NewMessageNotifier(context) {
    this.context = context;
    context.component('new-message-notifier', this);
    this.ws = null;
    this.list = $("#new-message-table").propertygrid({
        data: [],
        columns: [[{field: 'name', title: 'Name', width: 150}, {field: 'value', title: 'Value', width: 150}]]
    });
    this.init();
}

NewMessageNotifier.prototype = {
    init() {
        this.initWs();
    },
    initWs() {
        const _this = this;
        this.ws = new WebSocket(apiUrl.ws.newMessage);
        this.ws.onopen = e => {
            _this.onWsOpen(e);
        };
        this.ws.onmessage = e => {
            _this.onMessage(e.data);
        };
        this.ws.onclose = e => {
            _this.onWsClose(e);
        };
        this.ws.onerror = e => {
            console.log(e);
            _this.onWsError(e);
        }
    },
    onWsOpen(data) {
        this.list.propertygrid('appendRow', {name: '已连接', value: data ? data : ''});
    },
    onMessage(data) {
        data = JSON.parse(data);
        this.list.propertygrid('appendRow', {name: data.openId, value: data.msg});
    },
    onWsClose(data) {
        this.list.propertygrid('appendRow', {name: '连接关闭', value: data ? data : ''});
    },
    onWsError(e) {
        this.list.propertygrid('appendRow', {name: '连接异常', value: e});
    }
};

function MaterialForm(context) {
    this.context = context;
    context.form('material', this);
    this.forms = {};
    this.init();
}

MaterialForm.prototype = {
    init() {
        this.forms.create = $("#form-material-create");
    },
    submitCreate() {
        const _this = this;
        const form = this.forms.create;
        form.form('submit', {
            url: apiUrl.material.create,
            onSubmit() {
                $.messager.progress();
                if (!form.form('validate')) {
                    $.messager.progress('close');
                    return false;
                }
                return true;
            },
            success(data) {
                $.messager.progress('close');
                Util.show(data);
                _this.context.window('material').windows.create.dialog('close');
            }
        });
    }
};

function AutoReplyRuleForm(context) {
    this.context = context;
    context.form('auto-reply-rule', this);
    this.forms = {};
    this.init();
}

AutoReplyRuleForm.prototype = {
    init() {
        this.forms.create = $("#form-auto-reply-rule-create");
    },
    submitCreate() {
        const _this = this;
        const form = this.forms.create;
        form.form('submit', {
            url: apiUrl.autoReplyRule.create,
            onSubmit() {
                $.messager.progress();
                if (form.form('validate')) {
                    return true;
                } else {
                    $.messager.progress('close');
                    return false;
                }
            },
            success(data) {
                $.messager.progress('close');
                Util.show(data);
                _this.window('auto-reply-rule').windows.create.dialog('close');
            }
        });
    }
};

function AdminForm(context) {
    context.form('admin', this);
    this.context = context;
    this.forms = {};
    this.init();
}

AdminForm.prototype = {
    init() {
        this.forms.create = $("#form-admin-create");
    },
    submitCreate() {
        const _this = this;
        $.messager.progress();
        this.forms.create.form('submit', {
            onSubmit() {
                return _this.forms.create.form('validate');
            },
            success(data) {
                $.messager.progress('close');
                Util.show(data);
                _this.context.window('admin').closeCreateWindow();
                _this.context.table('admin').datagrid('reload');
            }
        });
    }
};

$(function () {
    Util.checkLoginStatus(res => {
        if (res.code === 0) {
            //已经登录状态
            const context = new Context();
            new Menu(context);
            new ContentTab(context);
            new UserService(context);
            new KfService(context);
            new NewMessageNotifier(context);
            new MaterialService(context);
            new MaterialWindow(context);
            new MaterialForm(context);
            new AutoReplyRuleService(context);
            new AutoReplyRuleWindow(context);
            new AutoReplyRuleForm(context);
            new AdminService(context);
            new AdminWindow(context);
            new AdminForm(context);
        } else {
            //未登录状态
            alert('未登录');
            window.location.href = '/login.html';
        }
    });
});